package com.admin.boot.common.interceptor;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.admin.boot.common.utils.RedisUtil;
import com.admin.boot.modules.system.entity.SysUser;
import com.admin.boot.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @version v3.0
 * @Description: TODO
 * @author: jeecg-boot
 * @date: 2024-02-03
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {



    @Autowired
    private ISysUserService sysUserService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod){
            SaIgnore loginIgnore = ((HandlerMethod) handler).getMethodAnnotation(SaIgnore.class);
            if (loginIgnore !=null){
                return true;
            }
        }
        if (StpUtil.isLogin()){
            SysUser user = (SysUser)StpUtil.getSession().get("user");
            if (user == null){
                String userId = StpUtil.getLoginIdAsString();
                user = sysUserService.getById(userId);
                StpUtil.getSession().set("user",user);
            }
            return true;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
